package com.haixiaoke.flat.houseMember.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.auth.AuthCheck;
import com.haixiaoke.saas.auth.ali.service.AliAuthService;
import com.haixiaoke.saas.common.annotation.RepeatSubmit;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.houseMember.domain.HouseMember;
import com.haixiaoke.saas.houseMember.service.IHouseMemberService;
import com.haixiaoke.saas.lock.domain.HouseLock;
import com.haixiaoke.saas.lock.service.IHouseLockService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import com.haixiaoke.token.FrontTokenComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * 房屋成员Controller
 *
 * @author qixi
 * @date 2024-03-07
 */
@RestController
@RequestMapping("/front/house/member")
public class FlatHouseMemberController extends BaseController {
    @Autowired
    private IHouseMemberService houseMemberService;
    @Autowired
    private FrontTokenComponent frontTokenComponent;
    @Autowired
    private AliAuthService aliAuthService;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IUserConsumerService userConsumerService;
    @Autowired
    private IHouseLockService houseLockService;

    /**
     * 获取用户入住房屋信息
     */
    @GetMapping(value = "/houseList")
    @AuthCheck
    public AjaxResult getHouseList(HouseMember houseMember) {
        houseMember.setUserId(frontTokenComponent.getUserId());
        return success(houseMemberService.getHouseList(houseMember));
    }


    /**
     * 获取入住人信息
     */
    @GetMapping(value = "/memberInfo/{orderId}")
    @AuthCheck
    public AjaxResult getMemberInfo(@PathVariable("orderId") String orderId) {
        return success(houseMemberService.getMemberInfo(orderId, frontTokenComponent.getUserId()));
    }


    /**
     * 获取房屋成员详细信息
     */
    @GetMapping(value = "/{memberId}")
    @AuthCheck
    public AjaxResult getInfo(@PathVariable("memberId") Long memberId) {
        return success(houseMemberService.selectHouseMemberByMemberId(memberId));
    }


    /**
     * 新增房屋成员信息
     */
    @PostMapping
    @AuthCheck
    @RepeatSubmit
    public AjaxResult add(@RequestBody @Valid HouseMember houseMember) {
        String memberPhone = houseMember.getMemberPhone();
        String orderId = houseMember.getOrderId();
        if (StrUtil.isNotEmpty(memberPhone)) {
            if (memberPhone.length() != 11) {
                return error("手机号格式不正确");
            }
            HouseMember member = houseMemberService.selectHouseMemberListByMemberPhone(memberPhone, orderId);
            if (ObjectUtil.isNotEmpty(member)) {
                return error("手机号已存在");
            }
        }
        HouseMember member = houseMemberService.selectHouseMemberListByIdCard(houseMember.getIdCard(), orderId);
        if (ObjectUtil.isNotEmpty(member)) {
            if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                return error("身份证号已存在");
            }
        }
        House house = houseService.selectHouseById(houseMember.getHouseId());
        if (ObjectUtil.isEmpty(house)) {
            return error("房屋不存在");
        }
        if (houseMemberService.countMemberNumberByOrderId(houseMember.getOrderId()) >= house.getCheckInNumber()) {
            return error("人数超过当前房屋限制的数量");
        }
        Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
        if (!flag) {
            return error("姓名或身份证有误，请核对后再试");
        }
        houseMember.setMemberType(HouseMember.MEMBER_TYPE_TENEMENT);
        houseMember.setCreateBy(frontTokenComponent.getLoginUser().getUser().getUserName());
        return toAjax(houseMemberService.insertHouseMember(houseMember));
    }


    /**
     * 修改房屋成员信息
     */
    @PutMapping
    @AuthCheck
    @RepeatSubmit
    public AjaxResult edit(@RequestBody @Valid HouseMember houseMember) {
        HouseMember sqlHouseMember = houseMemberService.selectHouseMemberByMemberId(houseMember.getMemberId());
        if (ObjectUtil.isEmpty(sqlHouseMember)) {
            return error("房屋成员不存在");
        }
        if (!StrUtil.equals(houseMember.getMemberName(), sqlHouseMember.getMemberName())
                || !StrUtil.equals(houseMember.getIdCard(), sqlHouseMember.getIdCard())) {
            Boolean flag = aliAuthService.identityCheck(houseMember.getMemberName(), houseMember.getIdCard());
            if (!flag) {
                return error("姓名或身份证有误，请核对后再试");
            }
        }
        String memberPhone = houseMember.getMemberPhone();
        if (StrUtil.isNotEmpty(houseMember.getMemberPhone())) {
            if (memberPhone.length() != 11) {
                return error("手机号格式不正确");
            }
            HouseMember member = houseMemberService.selectHouseMemberListByMemberPhone(memberPhone, sqlHouseMember.getOrderId());
            if (ObjectUtil.isNotEmpty(member)) {
                if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                    return error("手机号已存在");
                }
            }
        } else {
            houseMember.setMemberPhone(null);
        }

        HouseMember member = houseMemberService.selectHouseMemberListByIdCard(houseMember.getIdCard(), sqlHouseMember.getOrderId());
        if (ObjectUtil.isNotEmpty(member)) {
            if (!Objects.equals(member.getMemberId(), houseMember.getMemberId())) {
                return error("身份证号已存在");
            }
        }
        houseMember.setUpdateBy(frontTokenComponent.getLoginUser().getUser().getUserName());
        return toAjax(houseMemberService.updateHouseMember(houseMember));
    }


    /**
     * 住客认证
     */
    @PutMapping("/authentication")
    @AuthCheck
    @RepeatSubmit
    public AjaxResult authentication(@RequestBody @Valid HouseMember houseMember) {
        HouseMember sqlHouseMember = houseMemberService.selectHouseMemberByMemberId(houseMember.getMemberId());
        if (ObjectUtil.isEmpty(sqlHouseMember)) {
            return error("房屋成员不存在");
        }
        List<HouseLock> houseLockList = houseLockService.selectHouseLockByHouseIdAndLockState(houseMember.getHouseId(), HouseLock.LOCK_STATE_FROZEN);
        if (CollectionUtil.isNotEmpty(houseLockList)) {
            throw new ServiceException("该设备为冻结状态，无法进行认证，请联系管理员");
        }
        if (StrUtil.isNotEmpty(houseMember.getFacePhoto())) {
            AjaxResult ajaxResult = aliAuthService.faceAuth(houseMember.getMemberName(), houseMember.getIdCard(), houseMember.getFacePhoto());
            if (!ajaxResult.get("code").equals(200)) {
                return ajaxResult;
            }
        } else {
            return error("请上传人脸照片");
        }
        sqlHouseMember.setMemberName(houseMember.getMemberName());
        sqlHouseMember.setIdCard(houseMember.getIdCard());
        sqlHouseMember.setFacePhoto(houseMember.getFacePhoto());
        sqlHouseMember.setUpdateBy(frontTokenComponent.getLoginUser().getUser().getUserName());
        return toAjax(houseMemberService.authentication(sqlHouseMember));
    }


    /**
     * 删除房屋成员
     */
    @DeleteMapping("/{memberId}")
    @AuthCheck
    @RepeatSubmit
    public AjaxResult remove(@PathVariable Long memberId) {
        return toAjax(houseMemberService.deleteHouseMemberByMemberId(memberId));
    }
}
